package net.cz.wc.command;

import java.io.File;
import java.sql.Connection;

import net.cz.wc.data.ConnectionManager;
import net.cz.wc.main.Context;
import net.cz.wc.parser.AccessParser;

public class AccessCommand implements Command {

	public void execute(String args[]) {
		Connection conn = null;
		try {
			conn = ConnectionManager.getConnection();
			conn.setAutoCommit(false);
			Context.getContext().addDebugMessage("AccessCommand.execute()");
			
			if (!validateArgs(args)) {
				return;
			}
			
			new AccessParser().parse(new File(args[1]), conn);
			
			conn.commit();
		} catch (Exception ee) {
			Context.getContext().printException(ee);
			try {
				conn.rollback();
			} catch (Exception iieee) {
				iieee.printStackTrace();
			}
		} finally {
			ConnectionManager.closeConnection(conn);
		}
	}
	
	private boolean validateArgs(String args[]) {
		if (args.length != 2) {
			Context.getContext().addErrorMessage("Invalid params");
			Context.getContext().addErrorMessage(usage);
			return false;
		}
		
		if (!new File(args[1]).isFile()) {
			Context.getContext().addErrorMessage("File '" + args[1] + "' doesn't exist");
			return false;
		}
		
		return true;
	}
	
	String usage = 
			"use access parameter followed by a file name: " +
			"java -jar file.jar access <file>";
}
